//
// Created by bigknife on 14-6-20.
// Copyright (c) 2014 shanglu. All rights reserved.
//

#import "AFHTTPRequestOperationManager.h"
#import "AFChengShangApiInvoker.h"
#import "ApiResponse.h"
#import "ApiResponse.h"
#import "VMCMacros.h"

@interface AFChengShangApiInvoker ()
@property(nonatomic, strong) AFHTTPRequestOperationManager *requestOperationManager;
@property(nonatomic, strong) NSString *baseUrl;
@end

@implementation AFChengShangApiInvoker {

}

- (void)request:(NSURLRequest *)request callback:(API_CALLBACK)callback {
	__weak AFChengShangApiInvoker *weakSelf = self;
	AFHTTPRequestOperation *operation = [self.requestOperationManager HTTPRequestOperationWithRequest:request
																							  success:^(AFHTTPRequestOperation *requestOperation, id responseObj){
				[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
				DLog(@"OK, request %@ response is %@ msg = %@", requestOperation.request, responseObj,responseObj[@"msg"]);
				if (callback) {
					ApiResponse *apiResponse = nil;
					@try {
						apiResponse = [[ApiResponse alloc] initWithDictionary:responseObj];
						if (!apiResponse.success && [weakSelf.delegate respondsToSelector:@selector(handleError:response:)]) {
							[weakSelf.delegate handleError:requestOperation.response.statusCode response:apiResponse];
						}
						
						callback(requestOperation.response.statusCode, apiResponse, YES);
					}
					@catch (NSException *exception) {
						DLog("Exception occurred: %@, %@", exception, [exception userInfo]);
						id <AFIdonglerApiInvokerDelegate> o = weakSelf.delegate;
						if ([o respondsToSelector:@selector(handleError:response:)]) {
							[o handleError:requestOperation.response.statusCode response:apiResponse];
						}
						if (callback) {
							callback(0, nil, NO);
						}
					}

				}
			}
																							  failure:^(AFHTTPRequestOperation *requestOperation, NSError *error){
				[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
				DLog(@"ERROR! request %@ statusCode is %i, \n\r%@",requestOperation.request, (int)requestOperation.response.statusCode, error);
				id <AFIdonglerApiInvokerDelegate> o = weakSelf.delegate;
				if ([o respondsToSelector:@selector(handleError:response:)]) {
					[o handleError:requestOperation.response.statusCode response:nil];
				}
				if (callback) {
					callback(requestOperation.response.statusCode, nil, NO);
				}
			}];
	[self.requestOperationManager.operationQueue addOperation:operation];
}

+ (id)apiInvokerWithBaseUrl:(NSString *)baseUrl {
	AFChengShangApiInvoker *invoker = [[AFChengShangApiInvoker alloc] init];
	invoker.baseUrl = baseUrl;
	assert(invoker.baseUrl);
	invoker.requestOperationManager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:invoker.baseUrl]];
//	invoker.requestOperationManager.responseSerializer.acceptableContentTypes = nil;
	return invoker;
}

@end